﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Dispatching
{
    public partial class MaintenanceBillListView : UserControl, IView
    {
        //当前页  
        private int _pageIndex = 0;
        //总共几页
        private int _pageCount = 0;
        Promise _promise = new Promise();

        public MaintenanceBillListView()
        {
            InitializeComponent();
            this.ctlGrid.EmbeddedNavigator.ButtonClick += new DevExpress.XtraEditors.NavigatorButtonClickEventHandler(EmbeddedNavigator_ButtonClick);
        }

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("view", Resources.isView, "查看", btnReview_Click))
                 .AddAction(new ActionNode("maintain", Resources.isDispatchingBookList, "接待开单", btnCreateMaintainBill_Click))
                  .AddAction(new ActionNode("dispact", Resources.isDispatchingOrderList, "派工施工", btnDipact_Click) { IsShow = false })
                .AddAction(new ActionNode("refund", Resources.isGetMaterial, "领料退料", btnMaterial_Click) { IsShow = false })
                  .AddAction(new ActionNode("checked", Resources.isSettling, "订单结算", btnSettleMent_Click) { IsShow = false })
                  .AddAction(new ActionNode("checkedOut", Resources.isSettling, "订单收银", btnCheckOut_Click) { IsShow = false })
                  .AddAction(new ActionNode("carOut", Resources.isBus, "车辆出厂", btnCarOutClick) { IsShow = false })
               .AddAction(new ActionNode("refresh", Resources.isRefresh, "刷新", btnRefresh_Click));
        }
        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs.Result)
            {
                RefreshData();
            }
        }
        public void Active(ViewActiveArgs args)
        {
            _promise.Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    ctlLookUpEditStatus.BindMaintenanceBillQueryStatus(true);
                    _promise.Resolve();
                }));
            })
            .Then(RefreshData)
            .Run();
        }

        public ViewHeader GetHeader()
        {
            return new ViewHeader("服务单列表");
        }
        #endregion

        #region Method
        /// <summary>
        /// 获取每页条数限制
        /// </summary>
        /// <returns></returns>
        private int GetPageLimit()
        {
            int pagesize = 25;
            return pagesize;
        }
        /// <summary>
        /// 数据绑定
        /// </summary>
        private void RefreshData()
        {
            DateTime? beginTime = null, endTime = null;
            if (!string.IsNullOrEmpty(txtBeginDate.Text.Trim()))
            {
                beginTime = Convert.ToDateTime(txtBeginDate.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtEndDate.Text.Trim()))
            {
                endTime = Convert.ToDateTime(txtEndDate.Text.Trim());
            }

            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                string filter = string.IsNullOrEmpty(this.txtFilter.Text.Trim()) ? "" : txtFilter.Text.Trim();
                PagedResult<WebRef.VMaintenanceBill> result = new Service.QueryService().QueryMaintenanceBillPageList(
                    filter,
                    beginTime,
                    endTime,
                    ModuleContext.Current.BusinessId,
                    ModuleContext.Current.StationId,
                    GetStatus().StatusArray,
                    GetStatus().ServiceItemStatusArray,
                    GetStatus().MaterialStatusArray,
                    _pageIndex * GetPageLimit(),
                    GetPageLimit());
                this.BeginInvoke(new Action(() =>
                {
                    this.HideMask();
                    if (result.IsSuccess)
                    {
                        ctlGrid.DataSource = null;
                        this.GVData.FocusedRowHandle = -1;
                        ctlGrid.Paginate<WebRef.VMaintenanceBill>(result, out _pageIndex, out _pageCount);
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
            this.ShowAction("dispact", false);
            this.ShowAction("refund", false);
            this.ShowAction("checked", false);
            this.ShowAction("checkedOut", false);
            this.ShowAction("carOut", false);
        }

        public Domain.Constant.MaintenanceBillQueryStatus.Item GetStatus()
        {
            var selectedItem = LookUpEditUtil.GetSelectObject<Domain.Constant.MaintenanceBillQueryStatus.Item>(this.ctlLookUpEditStatus);
            if (selectedItem == null)
            {
                return Domain.Constant.MaintenanceBillQueryStatus.All;
            }
            return selectedItem;
        }
        #endregion

        #region Action
        /// <summary>
        /// 查看详细信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReview_Click(object sender, object e)
        {
            if (this.GVData.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBill item = this.GVData.GetRow(this.GVData.FocusedRowHandle) as WebRef.VMaintenanceBill;
                if (item.Status == Domain.Constant.MaintenanceBillStatus.WaitDelivery ||
                   item.Status == Domain.Constant.MaintenanceBillStatus.Finished)
                {
                    UIContext.Current.ViewManager.SwitchView(new Settling.SettlementBillDetailView(item.Id));
                }
                else
                {
                    UIContext.Current.ViewManager.SwitchView(new Dispatching.MaintenanceBillDetailView(item.Id));
                }
            }
        }
        private void btnCreateMaintainBill_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.PopupView(new Create.CreateMaintenanceBillView(), new PopupViewArgs("接车派工"));
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, object e)
        {
            _pageIndex = 0;
            RefreshData();
        }
        /// <summary>
        /// 结算
        /// </summary>
        private void btnSettleMent_Click(object sender, object e)
        {
            if (this.GVData.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBill item = this.GVData.GetRow(this.GVData.FocusedRowHandle) as WebRef.VMaintenanceBill;
                UIContext.Current.ViewManager.SwitchView(new Dispatching.MaintenanceBillSettlementView(item.Id));
            }
        }
        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void EmbeddedNavigator_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            e.UpdatePageIndex(_pageCount, ref _pageIndex);
            RefreshData();
        }
        /// <summary>
        /// 派工施工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDipact_Click(object sender, object e)
        {
            if (this.GVData.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBill item = this.GVData.GetRow(this.GVData.FocusedRowHandle) as WebRef.VMaintenanceBill;
                UIContext.Current.ViewManager.SwitchView(new Dispatching.MaintenanceBillDispatchView(item.Id));
            }
        }
        /// <summary>
        /// 领料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMaterial_Click(object sender, object e)
        {
            if (this.GVData.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBill item = this.GVData.GetRow(this.GVData.FocusedRowHandle) as WebRef.VMaintenanceBill;
                UIContext.Current.ViewManager.SwitchView(new Dispatching.MaintenanceBillMaterialView(item.Id));
            }
        }
        /// <summary>
        /// 根据服务单状态显示按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVData_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (this.GVData.FocusedRowHandle > -1)
                {
                    WebRef.VMaintenanceBill entity = GVData.GetRow(GVData.FocusedRowHandle) as WebRef.VMaintenanceBill;
                    switch (entity.Status)
                    {
                        case Domain.Constant.MaintenanceBillStatus.WaitDispatching:
                            {
                                this.ShowAction("dispact", true);
                                if (entity.MaterialCount > 0)
                                {
                                    this.ShowAction("refund", true);
                                }
                                else
                                {
                                    this.ShowAction("refund", false);
                                }
                                this.ShowAction("checked", false);
                                this.ShowAction("checkedOut", false);
                                this.ShowAction("carOut", false);
                                break;
                            }
                        case Domain.Constant.MaintenanceBillStatus.Working:
                            {
                                if (entity.ServiceItemStatus == Domain.Constant.MaintenanceBillStatus.ServiceItemStatus.Wait
                                    || entity.ServiceItemStatus == Domain.Constant.MaintenanceBillStatus.ServiceItemStatus.PartialWait
                                    || entity.ServiceItemStatus == Domain.Constant.MaintenanceBillStatus.ServiceItemStatus.Working
                                    || entity.ServiceItemStatus == Domain.Constant.MaintenanceBillStatus.ServiceItemStatus.PartialWorking)
                                {
                                    this.ShowAction("dispact", true);
                                }
                                else
                                {
                                    this.ShowAction("dispact", false);
                                }
                                if (entity.MaterialCount > 0)
                                {
                                    this.ShowAction("refund", true);
                                }
                                else
                                {
                                    this.ShowAction("refund", false);
                                }
                                this.ShowAction("checked", false);
                                this.ShowAction("checkedOut", false);
                                this.ShowAction("carOut", false);
                                break;
                            }
                        case Domain.Constant.MaintenanceBillStatus.WaitSettling:
                            this.ShowAction("dispact", false);
                            this.ShowAction("refund", false);
                            this.ShowAction("checked", true);
                            this.ShowAction("checkedOut", false);
                            this.ShowAction("carOut", false);
                            break;
                        case Domain.Constant.MaintenanceBillStatus.WaitCheckOut:
                            this.ShowAction("dispact", false);
                            this.ShowAction("refund", false);
                            this.ShowAction("checked", false);
                            this.ShowAction("checkedOut", true);
                            this.ShowAction("carOut", false);
                            break;
                        case Domain.Constant.MaintenanceBillStatus.WaitDelivery:
                            this.ShowAction("dispact", false);
                            this.ShowAction("refund", false);
                            this.ShowAction("checked", false);
                            this.ShowAction("checkedOut", false);
                            this.ShowAction("carOut", true);
                            break;
                        default:
                            this.ShowAction("dispact", false);
                            this.ShowAction("refund", false);
                            this.ShowAction("checked", false);
                            this.ShowAction("checkedOut", false);
                            this.ShowAction("carOut", false);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 订单收银
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCheckOut_Click(object sender, object e)
        {
            if (this.GVData.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBill item = this.GVData.GetRow(this.GVData.FocusedRowHandle) as WebRef.VMaintenanceBill;
                UIContext.Current.ViewManager.SwitchView(new CheckOut.CheckOutSettlementBillView(item.Id, "Maintenance"));
            }
        }
        /// <summary>
        /// 车辆出厂
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCarOutClick(object sender, object e)
        {
            if (this.GVData.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBill item = this.GVData.GetRow(this.GVData.FocusedRowHandle) as WebRef.VMaintenanceBill;
                UIContext.Current.ViewManager.SwitchView(new Settling.SettlementBillDetailView(item.Id));
            }
        }
        /// <summary>
        /// 根据状态值显示对应文本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVData_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column.Name == "colStatusText")
            {
                WebRef.VMaintenanceBill item = this.GVData.GetRow(e.RowHandle) as WebRef.VMaintenanceBill;
                Common.StatusRender.RenderMaintenanceBillStatus(e, item);
            }
        }
        #endregion
    }
}
